import CosSDK from 'cos-wx-sdk-v5'
import { genNo, rtrim } from '@/utils/helper'
import * as $material from '@/api/material'
import * as $cos from '@/api/cos'

let CosAuth = {
  tmpSecretId: '',
  tmpSecretKey: '',
  sessionToken: '',
  expiredTime: '',
}

export default {
  async getCosAuth () {
    if (CosAuth.sessionToken) return CosAuth
    CosAuth = await $cos.getAuth()
    return CosAuth
  },
  async upload ({
    path,
    dir = '',
    type = 'audio',
    size = 0,
    meta = null
  }, options = {
    busket: 'ark-1256750454',
    region: 'ap-shanghai',
    progress: (info) => {}
  }) {
    if (!path) return

    let {busket, region, progress} = options
    // 获取配置信息
    let cosAuth = await this.getCosAuth()
    if (!cosAuth.sessionToken) return

    // 获取cos上传对像
    let cos = new CosSDK({
      /* eslint-disable */
      getAuthorization: function (options, callback) {
        callback({
          TmpSecretId: cosAuth.tmpSecretId,
          TmpSecretKey: cosAuth.tmpSecretKey,
          XCosSecurityToken: cosAuth.sessionToken,
          ExpiredTime: cosAuth.expiredTime
        })
      }
      /* eslint-enable */
    })

    // 上传文件到cos服务
    dir = rtrim(dir, '/')
    let key = dir ? `${dir}/${genNo()}` : genNo()
    let contentType = 'audio/mpeg'
    let rs = await new Promise((resolve, reject) => {
      cos.postObject({
        Bucket: busket,
        Region: region,
        Key: key,
        FilePath: path,
        ContentType: contentType,
        onProgress (info) {
          progress(info)
        }
      }, (err, data) => {
        if (err) reject(err)
        if (data.statusCode !== 200) {
          reject(new Error(data.statusCode))
        }
        resolve(data)
      })
    })

    // 保存附件信息
    let material = await $material.createMaterial({
      type,
      key,
      size,
      meta
    })

    return material
  }
}
